package main

import (
	"fmt"
	"os"

	"github.com/CIPFZ/collector/cmd"
	"github.com/CIPFZ/collector/internal/app"
	"github.com/CIPFZ/collector/internal/config"
	"github.com/CIPFZ/collector/internal/vars"
	"github.com/CIPFZ/collector/pkg/logger"

	"go.uber.org/zap"
)

func main() {
	// 1. Load configuration
	cfg, err := config.LoadConfig()
	if err != nil {
		_, _ = fmt.Fprintln(os.Stderr, "Failed to load configuration. Please check the file path or use --config:", err)
		os.Exit(vars.ExitCodeConfig)
	}

	// 2. Initialize logger
	log, err := logger.NewLoggerWithConfig(cfg.Logger)
	if err != nil {
		_, _ = fmt.Fprintln(os.Stderr, "Failed to initialize logger:", err)
		os.Exit(vars.ExitCodeRuntime)
	}
	defer func() { _ = log.Sync() }()

	// 创建应用实例
	collectorApp := app.NewCollector(log, cfg)

	// 设置信号处理
	app.SetupSignalHandling(collectorApp)

	// 创建并执行根命令
	rootCmd := cmd.NewRootCommand(collectorApp)
	if runErr := rootCmd.Execute(); runErr != nil {
		log.Error("Command execution failed", zap.Error(err))
		_, _ = fmt.Fprintln(os.Stderr, "Command execution failed:", err)
		os.Exit(vars.ExitCodeRuntime)
	}
}
